package com.zzb.ucenter.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzb.base.utils.StringUtil;
import com.zzb.ucenter.mapper.XcUserMapper;
import com.zzb.ucenter.model.dto.XcUserAdd;
import com.zzb.ucenter.model.po.XcUser;
import com.zzb.ucenter.service.XcUserRegister;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @Author zzb
 * @Date 2024/7/27 19:24
 * @Version 1.0
 * @description
 */
@Service
public class XcUserRegisterImpl extends ServiceImpl<XcUserMapper, XcUser> implements XcUserRegister {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private XcUserMapper xcUserMapper;
    @Resource
    private PasswordEncoder bCryptPasswordEncoder;

    @Override
    public boolean register(XcUserAdd xcUserAdd) {
        //获取验证码
        String checkcode = xcUserAdd.getCheckcode();
        //校验验证码
        String codeRedis = (String) redisTemplate.opsForValue().get("code" + xcUserAdd.getCellphone());
        if (StringUtil.isBlank(codeRedis)){
            throw new RuntimeException("验证码已过期");
        }
        if (!codeRedis.equals(checkcode)){
            throw new RuntimeException("验证码输入错误");
        }
        //验证码校验正确，获取两次密码
        String password = xcUserAdd.getPassword();
        String confirmpwd = xcUserAdd.getConfirmpwd();
        //对比输入两次密码
        if (!StringUtil.isNotEmpty(password) && password.equals(confirmpwd)){
            throw new RuntimeException("确认密码输入有误");
        }
        XcUser xcUser = new XcUser();
        BeanUtils.copyProperties(xcUserAdd,xcUser);
        String passwordDb = bCryptPasswordEncoder.encode(password);
        xcUser.setPassword(passwordDb);
        int insert = xcUserMapper.insert(xcUser);
        if (insert < 0) {
            throw new RuntimeException("用户创建失败");
        }
        return true;
    }
}
